package mysql

import (
	"enjoy_xxz/formdata/types"
	"errors"
	"fmt"
	"github.com/spf13/viper"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"log"
)

func WithMysql(hand func(db *gorm.DB) error) error {
	config := types.ViperData
	//解析
	err := viper.Unmarshal(&config)
	if err != nil {
		return errors.New("failed to unmarshal")
	}
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		config.Mysql.Username,
		config.Mysql.Password,
		config.Mysql.Host,
		config.Mysql.Port,
		config.Mysql.Database,
	)
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})

	if err != nil {
		return errors.New("mysql client failed,error: " + err.Error())
	}
	fmt.Println("mysql connection successful")
	defer func() {
		fmt.Println("关闭连接")
		dd, _ := db.DB()
		err := dd.Close()
		if err != nil {
			log.Printf("msyql close %v", err)

			return
		}
	}()
	return hand(db)
}
